import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';


import 'package:easy_image_viewer/easy_image_viewer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp/MemoryReceive.dart';
import 'package:flutterapp/Receive.dart';
import 'package:flutterapp/Sender.dart';
import 'package:flutterapp/data.pb.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sn_progress_dialog/progress_dialog.dart';
import 'package:udp/udp.dart';



void main() {
  runApp(const MyApp());
}

class Tile{
  late Uint8List? img;
  late String? img_name;
  late String? str;
  late String? path;

  ///
  /// 1 字符串 2 图片 3 文件
  ///
  late int type;
  Tile(this.type,this.img,this.str,this.img_name,this.path);
}

class IpHost{
  late String name;
  late Endpoint port;
  IpHost(this.name,this.port);
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: '同网内容互传工具',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home:MyHomePage(title: '同网内容互传工具'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}


class _MyHomePageState extends State<MyHomePage> {
  var list = <Tile>[Tile(1,null,"0.请确保2台设备都在同一个网络\n1.发送文件广播有概率会被路由器拦截\n2.发送文件不要使用.exe结尾\n3.若找不到设备可以自行添加设备，设备地址是局域网IP地址",null,null)];

  //接收对象
  var rec_file_list = Map<int,Receive>();
  var rec_memory_list = Map<int,MemoryReceive>();

  //发送对象
  var sen_obj_list=Map<int,Sender>();

  ///进度展示弹窗
  ProgressDialog? pd;

  var current_rec_total=0;

  void removeMemory(id){
    log('删除1 receive_id=$id');
    rec_memory_list.remove(id);
  }
  void removeFile(id){
    log('删除2 receive_id=$id');
    rec_file_list.remove(id);
  }

  void removeSen(id){
    log('删除 sender_id=$id');
    sen_obj_list.remove(id);
  }

  get _loacldir {
    if(Platform.isAndroid){
      return '/storage/emulated/0/';
    }else{
      return 'download/';
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    udpClient.close();
    _controller.dispose();
    editingController.dispose();
    nameEditingController.dispose();
    deviceEditingController.dispose();
    super.dispose();
  }

  void hide_pd(String msg,int duration){
    pd?.update(msg: msg);
    pd?.close(delay: duration);
    Future.delayed(Duration(milliseconds: duration+500),() {
      pd = null;
    });
  }
  bool is_show_pd(){
    if(pd!=null){
      return true;
    }
    return false;
  }
  void show_pd(BuildContext ctx,int value,int max,String msg){
    pd=ProgressDialog(context: ctx);
    pd?.show(max: max,msg: msg);
    pd?.update(value:value,msg: msg);
  }
  void update_pd(int value,String msg){
    pd?.update(value:value,msg: msg);
  }
  
  _MyHomePageState(){

    //temp = Image.network("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
    //test

    if(!Platform.isWindows){ //非WINDOW版本做权限检查
      Future.delayed(const Duration(milliseconds: 1000),() async{

        //授权文件权限
        if(!await Permission.storage.isGranted){
          var request = await Permission.storage.request();
          if(request.isDenied){
            exit(-1); //拒绝则强制退出
            return;
          }
        }
        if(!(await Permission.manageExternalStorage.isGranted)){
          var request = await Permission.manageExternalStorage.request();
          if(request.isDenied){
            exit(-1); //拒绝则强制退出
            return;
          }
        }
      });
    }

    hostList=<IpHost>[IpHost("广播", Endpoint.broadcast(port:const Port(8000))) ];
    editingController=TextEditingController();
    nameEditingController=TextEditingController();
    deviceEditingController=TextEditingController();
    log("测试 是否执行了多次UDP绑定");

    // UDP.bind(Endpoint.multicast(InternetAddress("192.168.1.19") ,port: const Port(8000))).then((rec){
    UDP.bind(Endpoint.any(port: const Port(8000))).then((rec){
      udpClient=rec;

      rec.asStream().listen((datagram){
        setState(() {
          // list.add("check! $len");
          // len+=1;
          if(datagram!=null){
            var msgpack =MsgPack.fromBuffer(datagram.data);
            log('msgpack type=${msgpack.type}');
            switch(msgpack.type){
              case 0:{
                //名字
                var netName =utf8.decode(msgpack.chunk);
                var has=false;
                for(var n in hostList){
                  if(n.port.address==datagram.address){
                    has=true;
                    //存在列表中，把名字修改
                    setState(() {
                      n.name=netName;
                    });
                    break;
                  }
                }
                if(!has){
                  hostList.add(IpHost(netName,Endpoint.unicast( datagram.address,port: Port(datagram.port))));
                }

              }
              case 1:{
                //消息
                list.add(Tile(1,null,utf8.decode(msgpack.chunk),null,null));
              }
              case 2:{
                //图片
                var fileChunk = FileChunkPack.fromBuffer(msgpack.chunk);
                if(fileChunk.packIndex==0){
                  var curObj =MemoryReceive(rec,Endpoint.unicast(datagram.address,port: Port(datagram.port)),fileChunk.id);
                  rec_memory_list[fileChunk.id]=curObj;
                }
                if(rec_memory_list.containsKey(fileChunk.id)){
                  var curObj=rec_memory_list[fileChunk.id];
                  curObj!.receive(fileChunk, 2).then((save_state){
                    if(!save_state){
                      if(curObj.lastErr!=null){
                        hide_pd(curObj.lastErr.toString(),3000);
                      }else{
                        hide_pd('接收失败2',3000);
                      }
                      return;
                    }
                    if(is_show_pd()){
                      update_pd(fileChunk.packIndex ,'接收中...');
                    }else{
                      show_pd(context,fileChunk.packIndex ,fileChunk.packLen-1,'接收中...');
                    }
                    if(fileChunk.packIndex==fileChunk.packLen-1){
                      update_pd(fileChunk.packIndex ,'已完成');
                      //
                      setState(() {
                        log('ui change');
                        save=curObj.output.toBytes();
                        save_name=fileChunk.name;
                        list.add(Tile(2,save,null,save_name,null));
                        removeMemory(fileChunk.id);

                      });

                      //UI部分
                      //延迟执行滚动到底部
                      Future.delayed(const Duration(milliseconds: 500),(){
                        _controller.jumpTo(_controller.position.maxScrollExtent);
                      });


                      //关闭进度弹窗
                      hide_pd('已完成',3000);

                    }
                  });
                }

              }
              case 3:{
                //文件
                var fileChunk = FileChunkPack.fromBuffer(msgpack.chunk);
                if(fileChunk.packIndex==0){
                  var recObj =Receive(rec,Endpoint.unicast(datagram.address,port: Port(datagram.port)),fileChunk.id,File(_loacldir+fileChunk.name));
                  rec_file_list[fileChunk.id]=recObj;
                }
                if(rec_file_list.containsKey(fileChunk.id)){
                  var recObj=rec_file_list[fileChunk.id];
                  recObj!.receive(fileChunk, 3).then((save_state){
                    if(!save_state){
                      if(recObj.lastErr!=null){
                        hide_pd(recObj.lastErr.toString(),3000);
                      }else{
                        hide_pd('接收失败1',3000);
                      }
                      return;
                    }
                    if(is_show_pd()){
                      update_pd(fileChunk.packIndex ,'接收中...');
                    }else{
                      show_pd(context,fileChunk.packIndex ,fileChunk.packLen-1,'接收中...');
                    }
                    if(fileChunk.packIndex==fileChunk.packLen-1){
                      update_pd(fileChunk.packIndex ,'已完成');
                      //
                      //数据部分
                      setState(() {
                        // save=ir.file;
                        save=Uint8List(0);
                        save_name='';
                        var path = _loacldir+fileChunk.name;
                        list.add(Tile(3,null,null,fileChunk.name,path));

                        removeFile(fileChunk.id);
                      });

                      //UI部分
                      //延迟执行滚动到底部
                      Future.delayed(const Duration(milliseconds: 500),(){
                        _controller.jumpTo(_controller.position.maxScrollExtent);
                      });

                      //关闭进度弹窗
                      hide_pd('已完成',3000);

                    }
                  });
                }
              }
              case 4:{

                //各种回执
                final check = FileChunkCheckPack.fromBuffer(msgpack.chunk);
                if(check.type==2){
                  if (sen_obj_list.containsKey(check.id)){
                    var sender = sen_obj_list[check.id];
                    sender!.send(check.packIndex+1);
                  }
                }else if(check.type==3){
                  if (sen_obj_list.containsKey(check.id)){
                    var sender = sen_obj_list[check.id];
                    sender!.send(check.packIndex+1);
                  }
                }
              }
              case 5:{
                //告知发送方名字
                if(strname==''){
                  strname=DateTime.now().millisecondsSinceEpoch.toString();
                }
                var remote_name = utf8.decode(msgpack.chunk);

                var has=false;
                for(var n in hostList){
                  if(n.port.address==datagram.address){
                    has=true;
                    //存在列表中，把名字修改
                    setState(() {
                      n.name=remote_name;
                    });
                    break;
                  }
                }
                if(!has){
                  //接收方将发送端保存起来
                  hostList.add(IpHost(remote_name,Endpoint.unicast( datagram.address,port: Port(datagram.port))));
                }

                udpClient.send( MsgPack(type: 0,chunk:  utf8.encode(strname) ).writeToBuffer(), Endpoint.unicast(datagram.address,port: Port(datagram.port)));
              }
            }
          }
        });
        //延迟执行滚动到底部
        Future.delayed(const Duration(milliseconds: 500),(){
          _controller.jumpTo(_controller.position.maxScrollExtent);
        });

      },onDone: (){
        log("测试 UDP消息接收完成");
      });
    });

    if(Platform.isWindows){
      NetworkInterface.list(includeLinkLocal: false,includeLoopback: false,type: InternetAddressType.IPv4).then((value){
        var ip='';
        for(var item in value){
          for(var item2 in item.addresses){
            if(ip!=''){
              ip='$ip / ';
            }
            ip='$ip${item2.address}';
          }
        }
        log('ip=$ip');
        setState(() {
          list[0].str='${list[0].str!} \n4.本机地址：$ip';
        });
      });
      InternetAddress.lookup(InternetAddress.anyIPv4.host);
    }else{
      NetworkInfo().getWifiIP().then((ip){
        log('ip=$ip');
        setState(() {
          list[0].str='${list[0].str!} \n4.本机地址：$ip';
        });
      });
    }

  }

  //当前设备的UDP网络传输对象
  late UDP udpClient;

  //接收者列表
  late List<IpHost> hostList;

  String str=""; //消息
  String strname=""; //名字
  String device_address='';//设备地址

  void textChange(txt){
    str=txt;
  }
  void textChange2(txt){
    strname=txt;
  }
  void textChange3(txt){
    device_address=txt;
  }

  //信息编辑控制器
  late TextEditingController editingController;

  //名字输入框控制器
  late TextEditingController nameEditingController;

  //设备地址输入框控制器
  late TextEditingController deviceEditingController;

  //内容接收者
  var receive_obj=Endpoint.broadcast(port: const Port(8000));

  //windows版本中选中效果
  var host_select=0;

  //列表滚动控制器
  final ScrollController _controller = ScrollController();

  Uint8List save=Uint8List(0); //长按保存图片使用
  String save_name=''; //长按保存图片使用

  void save_image() async {
    if(save.isNotEmpty){
      var dir=_loacldir;

      if(Platform.isWindows){
        // var t = DateTime.now();
        // var res = await FileSaver.instance.saveFile(name:save_name=='' ? 'file':save_name,bytes: save  );
        await File(dir+save_name).writeAsBytes(save);
        // Fluttertoast.showToast(msg: res.toString(),toastLength: Toast.LENGTH_SHORT);
        showDialog(context: context, builder: (ctx)=>Dialog( child: Padding(padding: EdgeInsets.all(8.0),child: Text(dir+save_name), ) ) );
      }else{

        await File(dir+save_name).writeAsBytes(save);
        var res = dir+save_name;

        // var res = await FileSaver.instance.saveFile(name:save_name=='' ? 'file':save_name,bytes: save  );
        // var res = await ImageGallerySaver.saveImage(save,name: save_name!='' ? save_name : null);
        showDialog(context: context, builder: (ctx)=>Dialog( child: Padding(padding: EdgeInsets.all(8.0),child: Text(res.toString()), ) ) );
        //Fluttertoast.showToast(msg: res.toString(),toastLength: Toast.LENGTH_SHORT);
      }
    }

  }
  void send_file() async{
    if(pd!=null){
      return;
    }

    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if(result!=null){
      var path = result.files.single.path!;
      var file = File(path);
      var len  =await file.length();
      var filename = path.replaceAll(file.parent.path, "").replaceAll('/', "").replaceAll('\\', "");
      var send = Sender(udpClient,receive_obj,null,file);
      sen_obj_list[send.id]=send;
      log("send_file = $filename id={${send.id}");
      send.send(0);

    }else{
      log("send_file = null");
    }
  }
  void send_image() async {
    if(pd!=null){
      return;
    }
    final picker = ImagePicker();
    final XFile? file=await picker.pickImage(source: ImageSource.gallery);
    if(file!=null){
      var send = Sender(udpClient,receive_obj,file,null);
      sen_obj_list[send.id]=send;
      log("send_image = ${file.name} id=${send.id}");
      send.send(0);

    }else{
      log("send_image = null");
    }
  }
  void change_name_press(){
    // utf8.encode('nam|$strname')
    udpClient.send( MsgPack(type: 0,chunk:  utf8.encode(strname) ).writeToBuffer(),Endpoint.broadcast(port: const Port(8000)) );

    for(var item in hostList){
      //告知列表中的用户的名字
      udpClient.send( MsgPack(type: 0,chunk:  utf8.encode(strname) ).writeToBuffer(), item.port);
    }

    log("发送名字 $strname");
  }
  void change_name(){
    nameEditingController.text=strname;
    showDialog(context: context, builder: (ctc)=>Dialog(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: nameEditingController,
              onChanged: textChange2,
              decoration:const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "请输入你的名字"
              ),
            ),
            Padding(padding: const EdgeInsets.fromLTRB(0.0,10.0,0.0,0.0),child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const Text('名字通知'),
                IconButton(onPressed: change_name_press, icon: const Icon(Icons.send)),
              ],
            ),)

          ],
        ),
      ),
    ));
  }
  void select_iphost2(IpHost? iphost,int index){
    if(iphost!=null){
      receive_obj=iphost.port;
      log('选择iphost ${iphost.port.address}');
      setState(() {
        host_select=index;
      });
    }
  }
  void select_iphost(IpHost? iphost){
    if(iphost!=null){
      receive_obj=iphost.port;
      log('选择iphost ${iphost.port.address}');
    }
  }
  void send_message() {
    if(str==''){
      return;
    }
    log("发送信息到 ${receive_obj.address!.address}:${receive_obj.port!.value}");
    //utf8.encode('str|$str')
    udpClient.send( MsgPack(type: 1,chunk: utf8.encode(str)).writeToBuffer() ,receive_obj);
    editingController.clear();
    str='';
  }
  void show_big_image(String name,Uint8List img){
    showImageViewer(context, Image.memory(img).image, );
  }
  void add_device_press(){
    device_address;
    var remote = Endpoint.unicast(InternetAddress.tryParse(device_address),port: const Port(8000));
    // setState(() {
    //   hostList.add(IpHost(device_address, remote));
    // });

    if(strname==''){
      strname=DateTime.now().millisecondsSinceEpoch.toString();
    }

    udpClient.send(MsgPack(type: 5,chunk: utf8.encode(strname)).writeToBuffer(), remote);
  }
  void add_device(){
    deviceEditingController.text=device_address;
    showDialog(context: context, builder: (ctc)=>Dialog(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: deviceEditingController,
              onChanged: textChange3,
              decoration:const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "请输入设备地址"
              ),
            ),
            Padding(padding: const EdgeInsets.fromLTRB(0.0,10.0,0.0,0.0),child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const Text('添加设备'),
                IconButton(onPressed: add_device_press, icon: const Icon(Icons.send)),
              ],
            ),)

          ],
        ),
      ),
    ));
  }
  void delete_device(int index){
    if(index==0){
      log('不执行删除');
      return;
    }
    setState(() {
      hostList.removeAt(index);
      if(Platform.isWindows){
        if(host_select==index){
          select_iphost2(hostList[0], 0);//选中广播选项
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {

    List<ListTile> list2 = [];
    for(var (k,i) in list.indexed){
      if(k==0 && Platform.isWindows){
        continue;
      }
      if(i.type==1){
        list2.add(ListTile(title: SelectableText(i.str!) ));
      }else if(i.type==2){
        list2.add(ListTile( leading:Image.memory(i.img!,width: 50.0, height: 50.0, fit: BoxFit.contain,) , title: const Text("长按保存图片"),
          onTap: (){
            show_big_image(i.img_name!,i.img!);
          },
          onLongPress: (){
          // i.img
          save=i.img!;
          save_name=i.img_name!;
          save_image();
        }, ));
      }
      else if(i.type==3){ //file
        list2.add(ListTile( leading:const Icon(Icons.file_download_done) , subtitle: Text(i.path!), title: Text(i.img_name!),
          onTap: (){
            // show_big_image(i.img_name!,i.img!);
          },
          onLongPress: (){
            //文件已保存
            // i.img
            // save=i.img!;
            // save_name=i.img_name!;
            // save_image();
          }, ));
      }
    }
    
    final screenWidth = MediaQuery.of(context).size.width;




    return Scaffold(
      appBar: Platform.isWindows ? null : AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body:Platform.isWindows ? Row( //桌面端 UI
        children: [
          Expanded(
            flex: 0,
            child: Container( width: 300,
                color: const Color.fromRGBO(224, 232, 255, 1.0),
                child: Padding(padding: EdgeInsets.all(8.0),
                  child:Column(
                    children: [
                      Container(
                        color: const Color.fromRGBO(191, 207, 255, 1.0),
                        child: Padding(padding: EdgeInsets.all(8.0),
                          child: SelectableText(list[0].str!),
                        ),
                      ),
                      //左边容器
                      Expanded(
                        flex: 1,
                        child: ListView.builder(itemBuilder: (ctx,index){
                          return ListTile(
                            onTap: (){ select_iphost2(hostList[index],index);  } ,
                            selected: host_select==index,
                            selectedColor: Color.fromRGBO( 255, 119, 119, 1.0),
                            leading: const Icon(Icons.network_cell),title: SelectableText(hostList[index].name) ,
                            trailing: index==0 ? null : IconButton(onPressed: (){ delete_device(index); } , icon:Icon(Icons.delete),),
                          );
                        },
                          shrinkWrap: true,
                          itemCount: hostList.length,
                        ),
                      ),
                      Expanded(
                        flex: 0,
                        child: Row(
                          children: [
                            IconButton(onPressed: add_device, icon: const Icon(Icons.add),tooltip: '添加可发送对象',),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          Expanded(
            flex:1,
            child: Column(
              children: [
                Expanded(
                flex: 1,
                  child: ListView.builder(itemBuilder: (ctx,index){
                    return list2[index];
                  },
                    controller: _controller,
                    shrinkWrap: true,
                    itemCount: list2.length,
                  ),
                ),
                Expanded(
                  flex: 0,
                  child: Row(
                    children: [
                      //按钮
                      Expanded(flex: 0, child:
                        IconButton(onPressed: change_name, icon: const Icon(Icons.account_box),tooltip: '通知当前设备名字给局域网中的其他设备',)
                      ),
                      Expanded(
                        flex:1,
                        child: TextField(
                          maxLines: null,
                          minLines: null,
                          keyboardType: TextInputType.multiline,
                          controller: editingController,
                          onChanged: textChange,
                          decoration:const InputDecoration(
                              border: OutlineInputBorder(),
                              hintText: "请输入发送的内容"
                          ),
                        ),),
                      Expanded(flex: 0, child:
                        IconButton(onPressed: send_message, icon: const Icon(Icons.send),tooltip: '发送内容',)
                      ),
                      Expanded(flex: 0, child:
                        IconButton(onPressed: send_image, icon: const Icon(Icons.image),tooltip: '发送图片',)
                      ),
                      Expanded(flex: 0, child:
                        IconButton(onPressed: send_file, icon: const Icon(Icons.file_upload),tooltip: '发送文件',)
                      ),
                    ],
                  ),
                )
              ],
            )
          )
        ],
      ) :
      Column( //移动端 UI
        // crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(flex:0,
            child:Row(
              children: [
                DropdownMenu<IpHost>(
                  width: screenWidth - 70.0,
                  onSelected: select_iphost,
                  initialSelection: hostList.first, dropdownMenuEntries: hostList.map<DropdownMenuEntry<IpHost>>((v){
                  return DropdownMenuEntry<IpHost>(value: v, label: v.name);
                }).toList(),
                ),
                Expanded(flex: 0, child:
                    Padding(padding: EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 0.0),
                      child:IconButton(onPressed: add_device, icon: const Icon(Icons.add),tooltip: '添加可发送对象',),
                    ),
                )
              ],
            ),
          ),
          // Expanded(flex: 0, child:temp ),
          Expanded(flex: 1, child:
            ListView.builder(itemBuilder: (ctx,index){
              return list2[index];
            },
              controller: _controller,
              shrinkWrap: true,
              itemCount: list2.length,
            ),
          ),
          Expanded( flex:0,child:
              Row(
                children: [
                  Expanded(flex: 0, child:
                    IconButton(onPressed: change_name, icon: const Icon(Icons.account_box),tooltip: '通知当前设备名字给局域网中的其他设备',)
                  ),
                  Expanded(
                    flex:1,
                    child: TextField(
                      maxLines: null,
                      minLines: null,
                      keyboardType: TextInputType.multiline,
                      controller: editingController,
                    onChanged: textChange,
                    decoration:const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: "请输入发送的内容"
                    ),
                  ),),
                  Expanded(flex: 0, child:
                    IconButton(onPressed: send_message, icon: const Icon(Icons.send),tooltip: '发送内容',)
                  ),
                  Expanded(flex: 0, child:
                    IconButton(onPressed: send_image, icon: const Icon(Icons.image),tooltip: '发送图片',)
                  ),
                  Expanded(flex: 0, child:
                  IconButton(onPressed: send_file, icon: const Icon(Icons.file_upload),tooltip: '发送文件',)
                  ),

                  // Expanded(flex: 0, child:
                  //   IconButton(onPressed: save_image, icon: const Icon(Icons.save_alt),tooltip: '下载图片',)
                  // ),
                ],
              ),


          ),

        ],
      ),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: _incrementCounter,
      //   tooltip: 'Increment',
      //   child: const Icon(Icons.add),
      // ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
